package com.bilibili.server.interceptor;

import com.alibaba.fastjson.JSON;
import com.bilibili.model.db.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * @author HuangRongFu
 * 2021/11/17 星期三7:17 下午
 */

/**
 * token的统一处理
 */
@Component
@Slf4j
public class TokenInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //记录请求的路径
        String requestMethod = request.getMethod();
        log.info("请求了路径: {}:{}", requestMethod, request.getRequestURI());
        if (handler instanceof HandlerMethod) {
            // 找出调用的哪个controller中的方法
            HandlerMethod method = (HandlerMethod) handler;
            if (null != method) {
                log.info("执行了: " + method.getShortLogMessage());
            }
        }

        //从请求头中获取token
        String token = request.getHeader("Authorization");
        if (StringUtils.isNotEmpty(token)) {
            //获取Redis中token 校验
            String tokenKey = "TOKEN_" + token;

            //判断获取到的token是否有效
            String loginUserJson = stringRedisTemplate.opsForValue().get(tokenKey);

            if (StringUtils.isNotEmpty(loginUserJson)) {
                //如果有值
                //取出登录用户信息,存入线程
                User loginUser = JSON.parseObject(loginUserJson, User.class);
                UserHolder.setUser(loginUser);
                log.info("当前用户id =========== {}", loginUser.getId());
                
                //验证成功后 续费三天
                stringRedisTemplate.opsForValue().set(tokenKey, loginUserJson, 3, TimeUnit.DAYS);

                //放行
                return true;
            }
        }
        //没值 返回401
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        return false;
    }


    /**
     * controller发生异常，照样执行
     *
     * @param: request
     * @param: response
     * @param: handler
     * @param: ex
     * @Return: void
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.remove();
    }
}
